package impl

import (
	"context"
	"net/http"

	"gitee.com/LangHuaHuachihua/blog-go/apps/blog"
	"gitee.com/LangHuaHuachihua/blog-go/common"
)

var _ blog.Service = &impl{}

func (i *impl) CreateBlog(ctx context.Context, in *blog.CreateBlogRequest) (*blog.Blog, error) {
	err := in.Validate()
	// logger.L().Debug().Msg(err.Error())
	if err != nil {
		return nil, err
	}
	//构造函数生成实例
	ins := blog.NewBlog(in)
	err = i.db.WithContext(ctx).Save(ins).Error
	// ins, err := i.Save(ctx, ins)
	if err != nil {

		return nil, common.NewResponse(ctx, 0, http.StatusInternalServerError, err.Error())
	}
	return ins, err
}

func (i *impl) UpdateBlog(ctx context.Context, in *blog.UpdateBlogRequest) (*blog.Blog, error) {
	return nil, nil
}
func (i *impl) DeleteBlog(ctx context.Context, in *blog.DeleteBlogRequest) (*blog.Blog, error) {
	return nil, nil
}
func (i *impl) DescribeBlog(ctx context.Context, in *blog.DescribeBlogRequest) (*blog.Blog, error) {
	return nil, nil
}
func (i *impl) QueryBlog(ctx context.Context, in *blog.QueryBlogRequest) (*blog.BlogSet, error) {
	blogSet := blog.NewBlogSet()
	query := i.db.WithContext(ctx).Model(blog.Blog{})

	//模糊查询,查询文章内容
	if in.Keywords != "" {
		query = query.Where("content LIKE ?", "%"+in.Keywords+"%")
	}
	if in.Author != "" {
		query = query.Where("content = ?", in.Author)
	}

	//分页offset 忽略前面多少个 Limit代表一页多少个
	//数据是一个列表[]blog 直接传入find 即可匹配
	err := query.
		Offset(in.Offset()).
		Limit(in.PageSize).
		Find(&blogSet.Items).
		Count(&blogSet.Total).
		Error
	//SELECT * FROM `blogs` WHERE content LIKE '%测试%' LIMIT 20
	if err != nil {
		return nil, err
	}
	return blogSet, nil
}
